import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:flutter_demo/chapter7-FunctionWidget/inherted-across-widget/ChangeNotifierProvider.dart';

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(
        title: const Text("Function Widget Demo"),
      ),
      body: ProviderWidget(),
    ),
  ));
}

class ProviderWidget extends StatefulWidget {
  @override
  _ProviderWidgetState createState() => _ProviderWidgetState();
}

class _ProviderWidgetState extends State<ProviderWidget> {

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ChangeNotifierProvider<CartModel>(
        data: CartModel(),
        child: Builder(builder: (context) {
          return Column(
            children: <Widget>[
              Builder(builder: (context){
                var cart = ChangeNotifierProvider.of<CartModel>(context);
                return Text("总价: ${cart.totalPrice}");
              },),
              Builder(builder: (context) {
                print("ElevatedButton build");
                return ElevatedButton(
                  child: const Text('添加商品'),
                  onPressed: () {
                    ChangeNotifierProvider.of<CartModel>(context, listen: false).add(Item(20.0, 1));
                  },
                );
              }),
            ],
          );
        },),
      ),
    );
  }
}

class CartModel extends ChangeNotifier {
  // 用于保存购物车中商品列表
  final List<Item> _items = [];

  // 用于保存购物车中商品列表
  UnmodifiableListView<Item> get items => UnmodifiableListView(_items);
  // 购物车中商品的总价
  double get totalPrice =>
      _items.fold(0, (value, item) => value + item.count * item.price);
  // 将 [item] 添加到购物车。这是唯一一种能从外部改变购物车的方法。0
  void add(Item item) {
    _items.add(item);
    // 通知监听器（订阅者），重新构建InheritedProvider， 更新状态。
    notifyListeners();
  }
}

class Item {
  Item(this.price, this.count);

  double price;
  int count;
}
